package com.example.informationEntry.util;

import com.example.informationEntry.entity.NaSecret;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;

public class UtilMethod {


    private static final Logger LOG = LoggerFactory.getLogger(UtilMethod.class);


    /**
     * @param @param  jsonStr
     * @param @return 设定文件
     * @return Map<String, Object>    返回类型
     * @throws
     * @Title: parseJSONToMap
     * @Description: TODO(json字符串格式化为Map)
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> parseJSONToMap(String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject json = JSONObject.fromObject(jsonStr);
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                Iterator<JSONObject> it = ((JSONArray) v).iterator();
                while (it.hasNext()) {
                    JSONObject json2 = it.next();
                    list.add(parseJSONToMap(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }


    public static NaSecret getKey(String account) {
        LOG.info("公钥私钥为空，则进行公钥私钥生成");
        NaSecret naSecret = new NaSecret();
        try {
            Map<String, String> keyMap = RSAUtils.createKeys();
            naSecret.setAccountPublicKey(keyMap.get("publicKey"));
            naSecret.setAccountPrivateKey(keyMap.get("privateKey"));
            naSecret.setGenerationTime(UtilMethod.unixLong());
            naSecret.setAccount(account);
            LOG.info("公钥私钥获取成功");
        }catch (Exception e){
            LOG.info("获取公钥私钥异常" + e.getMessage());
        }
        return naSecret;
    }


    /**
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: randomCode
     * @Description: TODO(每次调用生成一个随机数)
     */
    public static String randomCode() {
        Random rand = new Random();
        int randNumber = rand.nextInt(100000000 - 10000000 + 1) + 10000000;
        return String.valueOf(randNumber);
    }


    /**
     * @param @return 设定文件
     * @return Long    返回类型
     * @throws
     * @Title: unixString
     * @Description: TODO(获取系统当前时间戳)
     */
    public static Long unixLong() {
        return System.currentTimeMillis();
    }

    /**
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: getdingdan
     * @Description: TODO(生成唯一识别号)
     */
    public static String getUnidNumber() {
        String UuId = String.valueOf(java.util.UUID.randomUUID());
        UuId = UuId.substring(24, 36);
        return UuId.toUpperCase();
    }


    /**
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: getdingdan
     * @Description: TODO(获取当前时间)
     */
    public static String getTime(String format) {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat(format);
        return sf.format(date);
    }

    /**
     * 将时间戳转换为时间
     *
     * @param date
     * @param format
     * @return
     */
    public static String unixToTime(Long date, String format) {
        SimpleDateFormat sf = new SimpleDateFormat(format);
        return sf.format(date);
    }


    /**
     * 将时间转换为时间戳
     *
     * @param datestr 时间字符串
     * @param format  转换的格式
     * @return Long类型的时间戳
     */
    public static Long dateToUnix(String datestr, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.parse(datestr).getTime();
        } catch (Exception e) {
            LOG.error("时间转换方法DateToUnix()报错" + e.getMessage());
        }
        return null;
    }


    /**
     * @param @param
     * @return @return
     * @throws
     * @Title: getUuid
     * @Description: TODO(生成唯一识别的UUID)
     * @author sunbo@pgytesting.cn
     * @date 2019/4/4 16:58
     */
    public static String getUuid() {
        return String.valueOf(java.util.UUID.randomUUID()).toUpperCase();
    }

    /**
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: md5Encryption
     * @Description: TODO(32位加密加盐方法)
     */
    public static String md5Encryption(String passWord) {
        try {
            // 得到一个信息摘要器
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(passWord.getBytes());
            StringBuffer buffer = new StringBuffer();
            // 把每一个byte 做一个与运算 0xff;
            for (byte b : result) {
                // 与运算
                int number = b & 0xff;// 加盐
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
            }
            // 标准的md5加密后的结果
            return buffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param @param  unix
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: getUnixToTime
     * @Description: TODO(将秒转换为时间)
     */
    public static Map<String, String> getSecondToTime(Long unix) {
        Map<String, String> map = new HashMap<>();
        Long unix1 = 0L;
        Long unix2 = 0L;
        unix1 = unix / 60;
        unix2 = unix1 / 60;
        LOG.info("执行转换方法：将" + unix + "秒转换为" + String.valueOf(unix2 + "小时" + unix1 % 60 + "分" + unix % 60 + "秒"));
        StringBuffer time = new StringBuffer();
        StringBuffer time2 = new StringBuffer();
        if (unix >= 3600) {
            time.append(unix2 + ":");
            time2.append(unix2 + " hours, ");
        }
        if (unix >= 60) {
            time.append(unix1 % 60 + ":");
            time2.append(unix1 % 60 + " minutes, ");
        }
        map.put(ConstantParam.PARAM_ENGLISH, String.valueOf(time.append(unix % 60)));
        map.put(ConstantParam.PARAM_CHINESE, String.valueOf(time2.append(unix % 60 + " seconds")));
        return map;
    }


    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */

    public static boolean isNumeric(String str) {
        Matcher isNum = ConstantParam.NUMBER_PATTERN.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


    /**
     * @param @param  num
     * @param @return 设定文件
     * @return double    返回类型
     * @throws
     * @Title: getTwoDecimal
     * @Description: TODO(保留两位小数 ， 四舍五入)
     */
    public static Double getTwoDecimal(Double num) {
        DecimalFormat dFormat = new DecimalFormat("#.00");
        String yearString = dFormat.format(num);
        Double temp = Double.valueOf(yearString);
        return temp;
    }


    /**
     * 获得该月最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }


    /**
     * 计算学号
     *
     * @param number 数据库最大学号
     * @return 下一位学号
     */
    public static String getNumberMax(String number) {
        String a = number.substring(0, 11);
        String c = number.substring(11);
        StringBuffer b = new StringBuffer();
        for (int i = 1; i < c.length(); i++) {
            b.append(0);
        }
        b.append(Integer.valueOf(c) + 1);
        return a + b;
    }

}
